<template>
  <div>
    <el-dialog
      :title="isEdit ? '编辑' : '新增部门'"
      :visible="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="部门名称" prop="name">
          <el-input
            v-model="form.name"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input
            v-model="form.code"
            style="width: 80%"
            placeholder="1-50个字符"
          />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select
            v-model="form.manager"
            style="width: 80%"
            placeholder="请选择"
          >
            <el-option
              v-for="obj in employeeList"
              :key="obj.id"
              :value="obj.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍">
          <el-input
            v-model="form.introduce"
            style="width: 80%"
            placeholder="1-300个字符"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFn">取 消</el-button>
        <el-button type="primary" @click="enterFn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeSimpleAPI, addDepartmentsAPI, getDepartDetailAPI, updateDepartmentsAPI } from '@/api'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    parentId: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean
    },
    originList: {
      type: Array,
      default: _ => [],
      // default(){
      //   return []
      // }
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
    // 判断是否能否找到对应的部门，如果找到了则返回该对象
      let arr = this.originList.map(item => item.code)
      // 如果存在该对象，则说明编码已经存在，抛出错误
      if (this.isEdit) {
        arr = this.originList.filter(item => item.id !== this.targetId).map(item => item.code)
      }
      arr.includes(value) ? callback(new Error(`此部门编辑${value},已经存在`)) : callback()
    }

    const validateName = (rules, value, callback) => {
      let arr = this.originList.filter(item => item.pid === this.targetId).map(item => item.name)

      if (this.isEdit) {
        const obj = this.originList.find(item => item.id === this.targetId)
        const pid = obj.pid
        arr = this.originList.filter(item => item.pid === pid && item.id !== this.targetId).map(item => item.name)
      }

      arr.includes(value) ? callback(new Error(`此部门名字${value},己径存在了`)) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employeeList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    dialogVisible() {
      if (this.dialogVisible === true) {
        this.getCompanyDetailFn()
      }
    }
  },
  created() {
    this.getEmployeesListFn()
  },
  methods: {
    handleClose(done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done()
      //   })
      //   .catch(_ => {})
      done()
    },
    // 取消按钮
    cancelFn() {
      this.$refs.deptForm.resetFields()
      this.$emit('update:dialogVisible', false)
    },
    // 确认按钮
    async enterFn() {
      this.$refs.deptForm.validate(async(valid) => {
        if (valid) {
          if (valid) {
            if (this.isEdit === true) {
              const res = await updateDepartmentsAPI({
                ...this.form,
                id: this.targetId
              })
              this.$message.success(res.$message)
            } else {
              const res = await addDepartmentsAPI({
                ...this.form,
                pid: this.targetId
              })
              this.$message.success(res.$message)
            }
            this.$emit('update:dialogVisible', false)
            this.$emit('resetList')
          }
        } else {
          this.$message.error('表单未通过')
        }
      })
      this.$refs.deptForm.resetFields()
    },
    async getEmployeesListFn() {
      const res = await getEmployeeSimpleAPI()
      this.employeeList = res.data
    },
    async getCompanyDetailFn() {
      if (this.isEdit === true) {
        const res = await getDepartDetailAPI(this.targetId)
        this.form = res.data
      }
    }

  }
}
</script>

<style>
</style>
